package com.gtlab1207.br_security.common;


import org.apache.commons.codec.binary.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class Util {
    public static  final Logger logger = LoggerFactory.getLogger(Util.class);


    /**
     * 字符串MD5转译
     * @param str
     * @return
     */
    public static String getStringMD5(String str){
        try {
            // 生成一个MD5加密计算摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            // 计算md5函数
            md.update(str.getBytes("UTF-8"));
            // digest()最后确定返回md5 hash值，返回值为8位字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            // BigInteger函数则将8位的字符串转换成16位hex值，用字符串来表示；得到字符串形式的hash值
            //一个byte是八位二进制，也就是2位十六进制字符（2的8次方等于16的2次方）
            String password = new BigInteger(1, md.digest()).toString(16);
            return password;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * MD5转译
     * @param in
     * @return
     */
    public static String getFileMD5(InputStream in) {
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int length;
            while ((length = in.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (in!= null){
                    in.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 一次在url添加一个参数
     * @param url
     * @param name
     * @param value
     * @return
     */
    public static String buildQuery(String url, String name, String value) {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
        params.add(name, value);
        UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(params).build();
        return uriComponents.toUriString();
    }

    /**
     * 一次在url中添加多个参数
     * @param url
     * @param map
     * @return
     */
    public static String buildQueryMulti(String url, MultiValueMap<String, String> map) {
        UriComponents uriComponents = UriComponentsBuilder.fromHttpUrl(url).queryParams(map).build();
        return uriComponents.toUriString();
    }



    /**
     * 获取一个文件夹下的所有的文件
     * @param fileDir
     * @return
     */
    public static File[] getFileList(String fileDir) {
        try {
            File dir = new File(fileDir);
            if (dir.exists() && dir.isDirectory()) {
                return dir.listFiles();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return new File[0];
    }

    /**
     * 批量下载，传入的参数是file
     */
    public static void downloadFileOfDicorty(HttpServletRequest request, HttpServletResponse response,
                                             File[] files, String name) throws IOException {
        //响应头的设置
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        name = processName(request.getHeader("USER-AGENT"), name);
        response.setHeader("Content-Disposition", "attachment;fileName=\"" + name + "\"");
        //设置压缩流:直接写入response，实现变压缩边下载
        ZipOutputStream zipOutputStream = null;
        //循环将文件写入压缩流
        DataOutputStream outputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            zipOutputStream.setMethod(ZipOutputStream.DEFLATED);    //设置压缩方法:边压缩边下载
            for (int i = 0; i < files.length; i ++) {
                if (files[i].exists()) {
                    zipOutputStream.putNextEntry(new ZipEntry((i + 1) + files[i].getName()));
                    outputStream = new DataOutputStream(zipOutputStream);
                    InputStream inputStream = new FileInputStream(files[i]);
                    byte[] b = new byte[2048];
                    int len = 0;
                    while ((len = inputStream.read(b)) != -1) {
                        outputStream.write(b, 0 , len);
                    }
                    inputStream.close();
                    zipOutputStream.closeEntry();
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (outputStream != null) {
                    //outputStream.flush();
                    outputStream.close();
                }
                if (zipOutputStream != null) {
                    zipOutputStream.flush();
                    zipOutputStream.close();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 处理文件名
     * @param agent
     * @param name
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String processName(String agent, String name) throws UnsupportedEncodingException {
        if (agent.contains("MSIE") || agent.contains("Trident")||agent.contains("Edge")) {
            return URLEncoder.encode(name, "UTF-8");
        }else if (agent.contains("Mozilla")){
            return new String(name.getBytes("UTF-8"), "iso8859-1");
        }else {
            return name;
        }
    }


    /**
     * 删除文件夹和里面的文件
     * @param folderPath
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除指定文件夹下所有文件
     * path 文件夹完整绝对路径
     * @param path
     * @return
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }
    /**
     * 删除单个文件
     *
     * @param filePath 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String filePath) throws IOException {
        File file = new File(filePath);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                return true;
            } else {
                throw new IOException("删除单个文件" + filePath + "失败！");
            }
        } else {
            return true;
        }
    }


    /**
     * 生成指定number个长度为length的随机数字加字母的不重复的字符串
     * @param length
     * @return
     */
    public static String getVerifyRandom(Integer length) {
        String val = "";
        Random random = new Random();
        //length为几位密码
        for (int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if ("char".equalsIgnoreCase(charOrNum)) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char) (random.nextInt(26) + temp);
            } else if ("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    /**
     * 随机指定范围内N个不重复的数
     * 最简单最基本的方法
     * @param min 指定范围最小值
     * @param max 指定范围最大值
     * @param n 随机数个数
     */
    public static Integer[] randomCommon(Integer min, Integer max, Integer n){
        if (n > (max - min + 1) || max < min) {
            return null;
        }
        Integer[] result = new Integer[n];
        Integer count = 0;
        while(count < n) {
            Integer num = (int)((Math.random() * (max - min)) + min);
            boolean flag = true;
            for (int j = 0; j < n; j++) {
                if(num == result[j]){
                    flag = false;
                    break;
                }
            }
            if(flag){
                result[count] = num;
                count++;
            }
        }
        return result;
    }

    /**
     * 读取文件为字符串
     * @param filePath
     * @return
     * @throws IOException
     */
    public static String fileToString(String filePath) throws IOException {
        StringBuffer buffer = new StringBuffer();
        BufferedReader bf= new BufferedReader(new FileReader(filePath));
        String s = null;
        while((s = bf.readLine())!=null){//使用readLine方法，一次读一行
            buffer.append(s.trim());
        }
        return buffer.toString();
    }
}
